<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <van-cell v-for="item in response" :key="item" :title="item.title" />
    </van-list>
  </van-pull-refresh>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import type { IListRequest } from '@/types/request';
import { useRouter } from 'vue-router';
import { getListApi } from '@/api';
import type { ITopic } from '@/types/topic';

const router = useRouter();
const response = ref<ITopic[]>([]);
const request = reactive<IListRequest>({
  page: 1,
  limit: 10,
  tab: '',
  total: 1000,
});

const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

const onLoad = () => {
  if (refreshing.value) {
    response.value = [];
    refreshing.value = false;
  }

  getListApi(request).then((res) => {
    response.value = [...response.value, ...res];

    loading.value = false;

    if (response.value.length >= request.total) {
      finished.value = true;
    } else {
      request.page++;
    }
  });
};

const onRefresh = () => {
  // 清空列表数据
  finished.value = false;

  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  onLoad();
};
</script>

<style lang="scss" scoped></style>
